package com.sxit.myproscenium.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.sxit.myproscenium.common.response.R;
import com.sxit.myproscenium.system.controller.form.AddAddressForm;
import com.sxit.myproscenium.system.entity.Address;
import com.sxit.myproscenium.system.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 前端控制器
 *
 * @author wcn
 * @since 2022-04-10
 */
@RestController
@RequestMapping("/system/address")
public class AddressController {

  @Autowired private IAddressService addressService;

  @SaCheckLogin
  @PostMapping("/addAddress")
  public R addAddress(@RequestBody @Valid AddAddressForm form) {

    long loginIdAsLong = StpUtil.getLoginIdAsLong();

    Address address = new Address();

    address.setOwnerId(loginIdAsLong);
    address.setDetailedAddress(form.getDetailedAddress());
    address.setPhone(form.getPhone());
    address.setTag(form.getTag());
    address.setConsigneeName(form.getConsigneeName());
    address.setCreateTime(LocalDateTime.now());

    boolean save = addressService.save(address);
    if (save) {
      return R.ok();
    } else {
      return R.error();
    }
  }

  @GetMapping("/getAddressList")
  public R getAddressList() {

    long loginIdAsLong = StpUtil.getLoginIdAsLong();
    List<Address> addressByUserId = addressService.getAddressByUserId(loginIdAsLong);
    return R.ok().put("data", addressByUserId);
  }

  @GetMapping("/getAddressById")
  public R getAddressById(@RequestParam("id") Long id) {

    Address byId = addressService.getById(id);

    return R.ok().put("data", byId);
  }
}
